import config from '@/common/config/config.js'
import reqFilter from '@/common/config/req-filter-config.js'
import Vue from 'vue'

const COMMONURL = config.api_base_url; //公共路径 
const LOGINURL = config.api_login_url; //登录接口
const FILEUPLOADURL = config.file_upload_url; //文件上传接口

const filter = new reqFilter(); //filter
let _this;
export default class Https {
	constructor() {
		this.isBebug = 0; //是否开启错误检测
		_this = this;
	};

	// post请求封装
	/**
	 * 
	 * @param {请求地址} url 
	 * @param {请求的数据} requestData 
	 * @param {是否验证错误} isFilter 
	 * @param {请求类型："POST" /  "GET" 默认为 "POST" } requestType 
	 */
	Request(url, requestData = {}, isShowCenterLodin = true, isFilter = true, requestType = "POST") {
		let requestHeader = {};
		if (requestType === "POST") {
			requestHeader = {
				"content-type": "application/json",
			}
		}
		// if (uni.getStorageSync('userInfos').openid) {
			try {
				requestHeader.token = uni.getStorageSync('userInfos').token;
				// requestHeader.openid = uni.getStorageSync('userInfos').openid;
			} catch (e) {

			}
		// }
		console.log(getApp().globalData.socketStatus);
		let promise = new Promise((resolve, reject) => {
			if (isShowCenterLodin) {
				uni.showLoading({
					title: "正在加载~"
				})
			}
			// 请求
			uni.request({
				url: COMMONURL + url,
				data: requestData,
				method: requestType,
				header: requestHeader,
				timeout: config.config_time_out,
				success: async res => {
					if (isFilter) {
						const err = await filter.systemCodeFilter(res.statusCode);
						if (err) return;
						const resState = await filter.resCodeFilter(res.data.code, this
							.isBebug === 3 ? {
								url: COMMONURL + url,
								data: requestData,
								method: requestType,
								header: requestHeader,
								response: res.data
							} : null);
						// 回滚请求
						resState == 'Rollback' ? _this.Request(url, requestData,
							isShowCenterLodin,
							isFilter, requestType,
						) : '';
						// 未登录， 拉取收取后回滚请求
						// console.log('http this:', this);
						// console.log(_this);
						resState == 'noLogin' ? resolve(_this.wxLogin2(null, url,
							requestData,
							isShowCenterLodin,
							isFilter, requestType,
						)) : '';
					}
					const timer = setTimeout(() => {
						clearTimeout(timer);
						uni.hideLoading();
					}, 500);
					resolve(res.data);
				},
				fail: (err) => {
					const timer = setTimeout(() => {
						clearTimeout(timer);
						uni.hideLoading();
					}, 500);
					uni.showToast({
						title: "连接超时~",
						icon: "none",
						duration: 2000
					})
				}
			});
		});
		return promise;
	}
	/**
	 * 微信app授权登录
	 * 
	 */
	loginByWechat() {
		return new Promise(resolve => {
			uni.getProvider({
				service: "oauth",
				success: (res) => {
					if (~res.provider.indexOf("weixin")) {
						uni.showLoading({
							title: "正在拉起微信授权..."
						});
						uni.login({
							provider: "weixin",
							success: async (res2) => {
								uni.hideLoading();
								let ress = await this.Request(
									LOGINURL, {
										openid: res2.authResult.openid,
										access_token: res2.authResult
											.access_token
									});
								if (ress.code == 1) {
									uni.setStorageSync('userInfo', ress.data);
									uni.showToast({
										title: "登录成功！",
										icon: "none"
									})
								}
								resolve(ress);
							},
							fail: (err) => {
								console.log(err);
								uni.showToast({
									title: "授权失败！",
									icon: "none"
								})
							},
							complete: () => {
								uni.hideLoading();
							}
						})
					}
				}
			})
		})
	}
	// 微信登录2
	wxLogin2(pid, ...option) {
		const isUseIv = true; //是否使用iv的方式登录（具体看后端）
		uni.showLoading({
			title: "正在登陆中..."
		});
		let promis = new Promise(resolve => {
			// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
			// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
			wx.getUserProfile({
				desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (res) => {
					resolve(res);
				},
				fail: err => {
					uni.hideLoading();
					console.log(err);
					if (err.errMsg.indexOf('can only be invoked by user TAP gesture') >= 0) {
						uni.showModal({
							content: '您还未登录，是否立即去登录？',
							success: (e) => {
								if (e.confirm) {
									uni.switchTab({
										url: '/pages/tabbers/my'
									})
								}
							}
						});
						return;
					}
					uni.showToast({
						title: '微信登录授权失败',
						icon: 'none'
					});
				}
			})
		}).then(res => {
			return new Promise(resolve => {
				uni.login({
					provider: 'weixin',
					success: res2 => {
						res2.info = res;
						resolve(res2);
					},
					fail() {
						uni.hideLoading();
					}
				});
			})
		}).then(res => {
			console.log(res);
			const uInfo = res.info.userInfo;
			return new Promise(async resolve => {
				const url = LOGINURL;
				let datas = {
					js_code: res.code,
					nickname: uInfo.nickName,
					avatar: uInfo.avatarUrl,
					gender: uInfo.gender,
					country: uInfo.country,
					province: uInfo.province,
					city: uInfo.city,
					language: uInfo.language,
					pid: pid ? pid : null
				};
				if (isUseIv) {
					datas = {
						code: res.code,
						iv: res.info.iv,
						encryptedData: res.info.encryptedData,
					}
				}
				let response = await this.Request(url, datas);
				console.log(response);
				if (response.code === 1) {
					uni.setStorageSync('userInfos', response.data);
					if (option.length > 0) {
						// 回滚
						resolve(this.Request(...option));
					}
					uni.showToast({
						title: "登录成功！",
						icon: "none"
					});
					resolve(response.data);
				} else {
					uni.showToast({
						title: "登录失败 请稍后再试",
						icon: "none"
					});
					resolve(null);
				}
			})
		})
		return promis;
	}

	/**
	 * 文件上传
	 * @param {Object} path  文件路径
	 */
	uploadFiles(path, isShowLoding = true) {
		return new Promise(resolve => {
			const uploadTask = uni.uploadFile({
				url: COMMONURL + FILEUPLOADURL, //仅为示例，非真实的接口地址
				filePath: path,
				name: 'file',
				header: {
					"content-type": "multipart/form-data",
				},
				formData: {
					path: 'goods'
				},
				success: uploadFileRes => {
					let res = JSON.parse(uploadFileRes.data);
					resolve(res.data);
				},
				fail: err => {
					uni.showToast({
						title: err,
						icon: "none"
					});
					resolve();
				}
			});
			if (isShowLoding) {
				uploadTask.onProgressUpdate(res => {
					let showInfo = '';
					if (res.progress <= 3) {
						showInfo = '开始上传';
					} else if (res.progress > 3 && res.progress < 98) {
						showInfo = `已上传${res.progress}%`;
					} else {
						showInfo = `即将完成`;
					}
					uni.showLoading({
						title: showInfo
					});
					if (res.progress === 100) {
						let timer = setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: "上传成功"
							});
							clearTimeout(timer);
						}, 1000);
					}
				});
			}
		})
	}
	/**
	 * 批量上传文件
	 * @param {Object} foleList 文件列表
	 */
	async uploadFilesMore(foleList) {
		uni.showLoading({
			title: "上传中~"
		})
		let resList = [];
		for (let item of foleList) {
			const path = await this.uploadFiles(item, false);
			resList.push(path.url);
		}
		uni.hideLoading();
		return resList;
	}
	/**
	 * 上传图片
	 */
	uploadImg(uploadMaxNum, sourceType = ['camera', 'album']) {
		return new Promise(resolve => {
			uni.chooseImage({
				count: uploadMaxNum, //默认9
				sourceType: sourceType,
				success: async chooseImageRes => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					let imgArr = [],
						i = 0
					for (i; i < tempFilePaths.length; i++) {
						let res = await this.uploadFiles(tempFilePaths[i]);
						imgArr.push(res);
					}
					resolve(imgArr);
				}
			});
		})
	}
	// 更改bebug状态
	updateIsBebug() {
		++this.isBebug;
		if (this.isBebug === 3) {
			uni.showToast({
				title: "已成功开启异常检测模式！",
				icon: "none",
				duration: 2500
			});
		} else if (this.isBebug > 3) {
			this.isBebug = 0;
		}
	}
	// 生成uuid
	uuid() {
		function S4() {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		}
		return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	}
}
